package com.xjc.market.acct.service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.xjc.infra.base.BaseService;
import com.xjc.infra.entity.ExecuteState;
import com.xjc.infra.entity.SessionContext;
import com.xjc.infra.util.PageFrom;
import com.xjc.market.acct.biz.LoginBiz;
import com.xjc.market.acct.entity.UserObjectEntity;
import com.xjc.market.acct.entity.table.AcOperator;
import com.xjc.market.frame.entity.Constant;
import com.xjc.market.frame.util.FrameUtil;

/**
 * 登录
 * @author liangcz
 * @Date   2017年9月18日 下午4:26:52
 * @version 1.0
 */
@RestController
@RequestMapping("/acct/service/LoginService")
public class LoginService extends BaseService{
	@Autowired
	LoginBiz loginBiz;
	/**
	 * 跳转到登录页面
	 * @author liangcz
	 * @date   2017年9月18日 下午4:33:19
	 * @return ModelAndView
	 */
	@RequestMapping("/goLogin")
	public ModelAndView goLogin(HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mav = new ModelAndView();
		mav.setViewName(PageFrom.getView("acct", "login"));
		return mav;
	}
	/**
	 * 登入
	 * @author liangcz
	 * @date   2017年9月6日 下午2:06:48
	 * @return void
	 */
	@RequestMapping("/login")
	public ModelAndView login(SessionContext sessionContext,HttpServletRequest request, HttpServletResponse response,HttpSession session,
			AcOperator acOperator){
		/**
		 * 1、判断是否已经登录，已经登录跳转到首页
		 * 2、登录成功，跳转到首页
		 * 3、登录失败，返回登录页面，展示失败提示
		 */
		ModelAndView modelAndView = new ModelAndView();
		UserObjectEntity userObjectEntity = FrameUtil.getUserObject(session);
		if(userObjectEntity != null){
			modelAndView.setViewName(PageFrom.getView("", "index"));
			return modelAndView;
		}
		if(StringUtils.isBlank(acOperator.getUserid())){
			modelAndView.setViewName(PageFrom.getView("acct", "login"));
			return modelAndView;
		}
		ExecuteState state = loginBiz.login(sessionContext,session,acOperator);
		if(state.isSuccess() == true){
			modelAndView.setViewName(PageFrom.getView("", "index"));
		}else{
			modelAndView.setViewName(PageFrom.getView("acct", "login"));
			modelAndView.addObject("state", state);
		}
		return modelAndView;
	}
	/**
	 * 登出
	 * @author liangcz
	 * @date   2017年9月18日 下午4:28:16
	 * @return void
	 */
	@RequestMapping("/logout")
	public ModelAndView logout(SessionContext sessionContext,HttpServletRequest request, HttpServletResponse response,HttpSession session){
		session.removeAttribute(Constant.USER_SESSION_ID);
		session.invalidate();
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName(PageFrom.getView("acct", "login"));
		return modelAndView;
	}
}
